package name.ekr.edu.threads.chatserver.client;

import static name.ekr.edu.threads.chatserver.Constants.ENCODING;
import static name.ekr.edu.threads.chatserver.Constants.HOST;
import static name.ekr.edu.threads.chatserver.Constants.PORT;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import name.ekr.edu.threads.chatserver.CommunicationError;
import name.ekr.edu.threads.chatserver.ConnectionError;
import name.ekr.edu.threads.chatserver.Server;

public class ServerProxy implements Server, Closeable {
	private static Logger logger = LoggerFactory.getLogger(ServerProxy.class);
	private Connector connector;
	private BufferedReader connectionReader;
	private PrintWriter connectionWriter;

	
	public ServerProxy(Connector connector) throws CommunicationError {
		this.connector = connector;
		connect();
	}

	
	@Override
	public void sendMessage(String message) {
		connectionWriter.println(message);
	}

	@Override
	public String getMessage() throws IOException {
		return connectionReader.readLine();
	}

	@Override
	public void close() throws ConnectionError {
		connector.close();
	}

	private void connect() throws CommunicationError {
		try {
			connectionReader = new BufferedReader(new InputStreamReader(connector.getSocket().getInputStream(), ENCODING));
			connectionWriter = new PrintWriter(new OutputStreamWriter(connector.getSocket().getOutputStream(), ENCODING), true);
		} catch (UnsupportedEncodingException e) {
			logger.error("", e);
			throw new CommunicationError("Encoding doesn't supported " + ENCODING, e);
		} catch (IOException e) {
			logger.error("", e);
			throw new CommunicationError("Can't establish connection to " + connector.getHost() + ":" + connector.getPort(), e);
		}
	}
}
